package copyengine.resource.file.sound
{
	import copyengine.resource.CEResConfig;
	import copyengine.resource.CEResManger;
	import copyengine.utils.GeneralUtils;

	import flash.events.Event;
	import flash.media.Sound;
	import flash.media.SoundChannel;

	public final class CESound
	{
		private var soundFileName:String;
		private var sound:Sound;
		private var soundChannel:SoundChannel;

		private var isPlayEvenNotLoad:Boolean;
		private var onSoundPlayFinishCallBack:Function;
		private var playLoopTime:int;
		private var isSoundInIdleState:Boolean;

		public function CESound()
		{
		}

		public function initialize(_soundFileName:String):void
		{
			//刚初始化时候Channel是Idle的
			isSoundInIdleState = true;
			isPlayEvenNotLoad = false;
			soundFileName = _soundFileName;
			//如果已经加载过则会直接回调onSoundFileLoadComplate函数
			CEResManger.instance.loadResFileByFileName(_soundFileName, onSoundFileLoadComplate);
		}

		private function onSoundFileLoadComplate():void
		{
			sound = CEResManger.instance.getResFile(soundFileName).getObject(null) as Sound;
			if (isPlayEvenNotLoad)
			{
				doPlay();
			}
		}

		/**
		 *播放当前声音
		 *
		 * @param _loopTime						播放的次数
		 * @param _isPlayEvenUnload			在没有加载完成的情况下，是否等加载完成后播放。
		 * 														如果为true则当前不播放但是一旦加载完成后就会播放,如果为false则不播放
		 * @param _onPlayFinish					在播放完成后回调
		 *
		 */
		public function play(_loopTime:int = 0, _isPlayEvenNotLoad:Boolean = false, _onPlayFinish:Function = null):void
		{
			//如果当前不为IdelState则不播放音乐,即使当前正在
			if (isSoundInIdleState)
			{
				isPlayEvenNotLoad = false;
				if (isSoundLoaded())
				{
					playLoopTime = _loopTime;
					onSoundPlayFinishCallBack = _onPlayFinish;
					doPlay();
				}
				else
				{
					if (_isPlayEvenNotLoad)
					{
						isSoundInIdleState = false;
						isPlayEvenNotLoad = true;
						playLoopTime = _loopTime;
						onSoundPlayFinishCallBack = _onPlayFinish;
					}
				}
			}
		}

		private function doPlay():void
		{
			releaseCurrentSoundChannel();
			soundChannel = sound.play(0, playLoopTime);
			GeneralUtils.addTargetEventListener(soundChannel, Event.SOUND_COMPLETE, onSoundPlayFinish);
			isSoundInIdleState = false;
		}

		private function onSoundPlayFinish(e:Event):void
		{
			isSoundInIdleState = true;
			onSoundPlayFinishCallBack && onSoundPlayFinishCallBack();
		}

		public function stop():void
		{
			soundChannel && soundChannel.stop();
			releaseCurrentSoundChannel();
		}

		/**
		 *返回当期的播放状态，是否空闲可以播放音乐
		 */
		public function isSoundIdle():Boolean
		{
			return isSoundInIdleState;
		}

		public function isSoundLoaded():Boolean
		{
			return CEResManger.instance.getResFile(soundFileName).loadState == CEResConfig.LOAD_STATE_LOADED;
		}

		private function releaseCurrentSoundChannel():void
		{
			isSoundInIdleState = true;
			if (soundChannel)
			{
				soundChannel.stop();
				soundChannel = null;
			}
		}


	}
}
